package com.test.stack;

/**
 * 使用一个数组stack[]来存储栈元素
 * 定义一个栈顶指针top，默认值为-1
 * 有元素入栈操作时，top++;stack[top]=data;
 * 出栈操作：int value = stack[top];top–;return value;
 */
public class ArrayStackDemo {
    public static void main(String[] args) {
        ArrayStack stack = new ArrayStack(4);
        stack.push(1);
        stack.push(2);
        stack.push(3);
        stack.list();
        stack.pop();
        stack.list();
    }
}

class ArrayStack {
    private int stack[];
    int top = -1;
    int max;

    public ArrayStack(int max) {
        stack = new int[max];
        this.max = max;
    }

    public boolean isFull() {
        return top == max;
    }

    public boolean isEmpty() {
        return top == -1;
    }

    public void push(int data) {
        if (isFull()) {
            System.out.println("栈满~~");
            return;
        }
        top++;
        stack[top] = data;
    }

    public int pop() {
        if (isEmpty()) {
            throw new RuntimeException("栈空");
        }
        int data = stack[top];
        top--;
        return data;
    }

    public void list() {
        if (isEmpty()) {
            System.out.println("栈空，没有数据~~");
            return;
        }
        //需要从栈顶开始显示数据
        for (int i = top; i >= 0; i--) {
            System.out.printf("stack[%d]=%d\n", i, stack[i]);
        }
    }
}
